package com.geese.module.wechat.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.geese.exception.BusinessException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geese.common.BaseController;
import com.geese.common.WXUtil;
import com.geese.common.util.DateUtil;
import com.geese.common.util.WebUtil;
import com.geese.module.wechat.core.WeChatConstants;
import com.geese.util.AesException;
import com.geese.util.SHA1;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Maps;

@Controller
public class WxAPI extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(WxAPI.class); 
	private static final String ENCODE_FORMAT = "utf-8";
	private static final String GRANT_TYPE = "authorization_code";
	
	private Cache<String,String> uriMap ;
	
	public WxAPI() {
		uriMap = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(60, TimeUnit.SECONDS)
				.build();
	}
	
	@RequestMapping(value = "/Auth/authorize", method = RequestMethod.GET)
    public String authorize(ModelMap modelMap, @RequestParam Map<String,String> reqContent) throws Exception {
		String clientRedirectUri = reqContent.get("redirect_uri");
		if(StringUtils.isEmpty(clientRedirectUri)){
			throw new BusinessException(120063);
		}
		if(clientRedirectUri.indexOf("{openid}") == -1){
			throw new BusinessException(120063);
		}
		if(!(StringUtils.startsWith(clientRedirectUri, "http://") || StringUtils.startsWith(clientRedirectUri, "https://")) ){
			throw new BusinessException(120063);
		}
		if(logger.isInfoEnabled()) {
			logger.info("clientRedirectUri : " + clientRedirectUri);
		}
		String uriKey = RandomStringUtils.randomAlphabetic(32);
		uriMap.put(uriKey, clientRedirectUri);
		 
		StringBuilder strb = new StringBuilder();
		strb.append("https://open.weixin.qq.com/connect/oauth2/authorize?")
			.append("appid=").append(WeChatConstants.APP_ID)
			.append("&redirect_uri=").append(URLEncoder.encode(WeChatConstants.REDIRECT_URI, ENCODE_FORMAT))
			.append("&response_type=code&scope=snsapi_base&state=").append(uriKey)
			.append("#wechat_redirect");
    	return "redirect:" + strb.toString() ;
    }
	
	@RequestMapping(value = {"/Auth/redirect","/Auth/redirect/"}, method = RequestMethod.GET)
    public String redirect(ModelMap modelMap, @RequestParam Map<String,String> reqContent) throws Exception {
		String clientUri = uriMap.getIfPresent(reqContent.get("state"));
		if(StringUtils.isEmpty(clientUri)) {
			throw new BusinessException(120064);
		}
		
		Map<String,String> params = Maps.newHashMap();
		params.put("appid", WeChatConstants.APP_ID);
		params.put("secret", WeChatConstants.APP_SECRET);
		params.put("code", reqContent.get("code"));
		params.put("grant_type", GRANT_TYPE);
		String response = WebUtil.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", params);
		JSONObject resObject = JSON.parseObject(response);
		if( resObject.get("errcode") != null){
			logger.error(response);
			logger.warn(resObject.get("errmsg").toString());
			throw new BusinessException(resObject.get("errmsg").toString());
		}
		
		String redirectUri = URLDecoder.decode(clientUri, ENCODE_FORMAT).replaceAll("\\{openid\\}", resObject.getString("openid"));
		if(logger.isInfoEnabled()) {
			logger.info("redirectUri : " + redirectUri);
		}
		return "redirect:" + redirectUri;
    }
	
	 /**
     * 获取JS-SDK调用凭证
     */
    @ResponseBody
    @RequestMapping(value = "/wechat/jsapi/config", method = RequestMethod.GET)
    public String getJsApiConfig(String url) {
        Map<String, String> map = Maps.newHashMap();
        map.put("jsapi_ticket", WXUtil.getJsApiTicket());
        map.put("url", url.split("#")[0]);
        map.put("noncestr", RandomStringUtils.randomAlphabetic(32));
        map.put("timestamp", Long.toString(DateUtil.getCurrentTimeStamp()));
        map.put("signature",WXUtil.createSign(map,WeChatConstants.APP_SECRET));
        map.put("appId", WeChatConstants.APP_ID);
        map.put("nonceStr", map.get("noncestr"));
        map.remove("jsapi_ticket");
        map.remove("noncestr");
        map.remove("url");
        return response(map);
    }
    
    /**
     * 校验微信与当前服务器的连通性
     */
    @RequestMapping(value = "/wechat/wx_conn_status", method = RequestMethod.GET)
    public void validConnection(String signature, String timestamp, String nonce, String echostr) {
        if (signature == null || "".equals(signature)) {
            printJson("error");
            return;
        }
        if (logger.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer("request params is [");
            sb.append("signature=").append(signature).append(",")
                    .append("timestamp=").append(timestamp).append(",")
                    .append("nonce=").append(nonce).append(",")
                    .append("echostr=").append(echostr).append("]");
            logger.debug(sb.toString());
        }
        try {
            String hexstr = SHA1.getSHA1(WeChatConstants.ACCESS_TOKEN, timestamp, nonce, WeChatConstants.ENCODING_AES_KEY);
            if (logger.isDebugEnabled()) {
                logger.debug("hexstr=" + hexstr);
            }
            if (signature.equals(hexstr)) {
                printJson(echostr);
                return;
            }
        } catch (AesException e) {
            e.printStackTrace();
        }
        printJson("error");
    }
    
	public static void main(String[] args) throws UnsupportedEncodingException {
		System.out.println(URLEncoder.encode("http://xe.igeese.cn/student/index.html#/login?openid={openid}", "UTF-8"));
	}
	
}
